﻿using SqlMapper.SqlElements;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Xml;

namespace SqlMapper
{
    public static class SqlBuilder
    {
        public static void AddChildren(XmlNode node, BaseTag dynamic)
        {
            var factory = new DeSerializerFactory();
            int count = node.ChildNodes.Count;
            for (int i = 0; i < count; i++)
            {
                var name = node.ChildNodes[i].LocalName;
                var deSerializer = factory.GetDeSerializer(name);

                if (deSerializer != null)
                    dynamic.AddChild(deSerializer.Deserialize(node.ChildNodes[i]));
            }
        }

        /// <summary>
        /// 拼接SQL
        /// 缺少查询参数部分
        /// </summary>
        /// <param name="select"></param>
        /// <param name="nvc"></param>
        /// <returns></returns>
        public static string Build(Select select, NameValueCollection nvc)
        {
            var sql = new StringBuilder(select.Sql);
            bool isOverridePrepend = false;
            foreach (string name in nvc.AllKeys)
            {
                string value = nvc[name];
                var tag = select.Statements.FirstOrDefault(b => b.Property == name && b.IsCondition(value));
                if (tag != null)
                {
                    if (isOverridePrepend == false && select.IsPrependAvailable)
                    {
                        sql.Append(select.Prepend);
                        isOverridePrepend = true;
                    }
                    else {
                        sql.Append(tag.Prepend);
                    }
                    sql.Append(tag.Sql);
                }
            }

            return sql.ToString();
        }
    }
}
